/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
// Copyright tang.  All rights reserved.
// https://gitee.com/inrgihc/dbswitch
//
// Use of this source code is governed by a BSD-style license
//
// Author: tang (inrgihc@126.com)
// Date : 2020/1/2
// Location: beijing , china
/////////////////////////////////////////////////////////////
package com.je.meta.service.dbswitch.service.impl.database;

import com.je.common.base.constants.table.TableType;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.model.database.ColumnDescription;
import com.je.meta.model.database.TableDescription;
import com.je.meta.model.database.type.ProductTypeEnum;
import com.je.meta.service.dbswitch.service.IDatabaseInterface;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 支持SQLServer2000数据库的元信息实现
 *
 * @author tang
 */
public class DatabaseSqlserver2000Impl extends DatabaseSqlserverImpl implements IDatabaseInterface {

    public DatabaseSqlserver2000Impl() {
        super("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    }

    @Override
    public ProductTypeEnum getDatabaseType() {
        return ProductTypeEnum.SQLSERVER2000;
    }

    @Override
    public Page queryTableList(Connection connection, String schemaName, String productId, String fuzzyValue
            , int intPage, int intLimit) {
        List<TableDescription> ret = new ArrayList<>();
        Set<String> uniqueSet = new HashSet<>();
        String[] types = new String[]{"TABLE", "VIEW"};
        try (ResultSet tables = connection.getMetaData()
                .getTables(this.catalogName, schemaName, "%", types);) {
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                if (uniqueSet.contains(tableName)) {
                    continue;
                } else {
                    uniqueSet.add(tableName);
                }

                TableDescription td = new TableDescription();
                td.setSchemaName(schemaName);
                td.setTableCode(tableName);
                td.setTableName(tables.getString("REMARKS"));
                if (tables.getString("TABLE_TYPE").equalsIgnoreCase("VIEW")) {
                    td.setTableType(TableType.VIEWTABLE);
                } else {
                    td.setTableType(TableType.PTTABLE);
                }
                ret.add(td);
            }
            return getPage(ret, intPage, intLimit);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TableDescription queryTableMeta(Connection connection, String schemaName,
                                           String tableName) {
        TableDescription tableDescription = new TableDescription();
        String[] types = new String[]{"TABLE", "VIEW"};
        try (ResultSet tables = connection.getMetaData()
                .getTables(this.catalogName, schemaName, "%", types);) {
            while (tables.next()) {
                String tableCode = tables.getString("TABLE_NAME");
                if (!tableName.equals(tableCode)) {
                    continue;
                }
                TableDescription td = new TableDescription();
                td.setSchemaName(schemaName);
                td.setTableCode(tableName);
                td.setTableName(tables.getString("REMARKS"));
                if (tables.getString("TABLE_TYPE").equalsIgnoreCase("VIEW")) {
                    td.setTableType(TableType.VIEWTABLE);
                } else {
                    td.setTableType(TableType.PTTABLE);
                }
                tableDescription = td;
            }
            return tableDescription;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<ColumnDescription> queryTableColumnMeta(Connection connection, String schemaName,
                                                        String tableName) {
        String sql = this.getTableFieldsQuerySQL(schemaName, tableName);
        List<ColumnDescription> ret = this.querySelectSqlColumnMeta(connection, sql);
        try (ResultSet columns = connection.getMetaData()
                .getColumns(this.catalogName, schemaName, tableName, null)) {
            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                String remarks = columns.getString("REMARKS");
                for (ColumnDescription cd : ret) {
                    if (columnName.equalsIgnoreCase(cd.getFieldName())) {
                        cd.setRemarks(remarks);
                    }
                }
            }
            return ret;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
